package com.qk.management.task;

import com.qk.common.util.AliYunOSSOperators;
import com.qk.entity.User;
import com.qk.management.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Component
public class ImageTask {
    @Autowired
    private UserService userService;

    @Autowired
    private AliYunOSSOperators aliYunOSSOperators;

    @Scheduled(cron = "0 0 0/1 * * ? ")
    public void deleteImage() {
        try {
            log.info("开始执行OSS图片清理任务");
            List<User> userList = userService.selectAll();
            List<String> validImagePaths = userList.stream()
                    .map(User::getImage)
                    .filter(image -> image != null && !image.isEmpty())
                    .collect(Collectors.toList());

            log.info("数据库中共有 {} 个有效图片路径", validImagePaths.size());
            aliYunOSSOperators.deleteExcept(validImagePaths);
            log.info("OSS图片清理任务执行完成");
        } catch (Exception e) {
            log.error("执行OSS图片清理任务时发生错误", e);
        }
    }
}
